<template>
  <basic-container>
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      ref="crud"
      :before-open="onBeforeOpen"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoad"
    >
      <template #security="{ row }">
        <div>
          {{ website.securityLists.find(i => i.value == row.security)?.label || row.security }}
        </div>
      </template>
      <template #isDirection="{ row }">
        <div>{{ row.hasChild ? '是' : '否' }}</div>
      </template>
      <template #status="{ row }">
        <div>{{ row.statusName }}</div>
      </template>
      <template #menu="scope">
        <el-button type="primary" text @click.stop="handlePublish(scope.row, scope.index)"
          >发布
        </el-button>

        <el-button type="primary" text @click.stop="handleUnPublish(scope.row, scope.index)"
          >取消发布
        </el-button>
      </template>
      <template #name="{ row }">
        <span>{{ row.name }}</span>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  publish,
  unpublish,
} from '@/api/position/position';
import option from '@/option/position/position';
import { mapGetters } from 'vuex';
import 'nprogress/nprogress.css';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      parentId: '-1',
      selectionList: [],
      option: option,
      data: [],
    };
  },
  mounted() {
    this.option.column[2].dicData = this.website.securityLists;
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.knowledgeClassification_add, false),
        viewBtn: this.validData(this.permission.knowledgeClassification_view, false),
        delBtn: this.validData(this.permission.knowledgeClassification_delete, false),
        editBtn: this.validData(this.permission.knowledgeClassification_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    onBeforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.security = String(this.form.security);
          this.form.isDirection = String(this.form.isDirection);
          this.form.isPublished = String(this.form.isPublished);
        });
      }
      done();
    },
    rowSave(row, done, loading) {
      if (!row.parentId) {
        row.parentId = -1;
      }
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      row = {
        id: row.id,
        name: row.name,
        code: row.code,
        note: row.note,
        security: row.security,
        hasChild: row.hasChild,
        isPublished: String(row.isPublished),
        isDirection: String(row.isDirection),
      };
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page) {
      this.loading = true;
      this.data = [];
      console.log(1, this.search);
      this.search.size = page.pageSize
      this.search.current = page.currentPage
      delete this.search.$security
      delete this.search.$isDirection
      
      getList(this.search).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleAdd(row) {
      if (row.id) {
        this.parentId = row.id;
      }
      const column = this.findObject(this.option.column, 'parentId');
      column.value = this.parentId;
      column.addDisabled = true;
      this.$refs.crud.rowAdd();
    },
    treeLoad(tree, treeNode, resolve) {
      let values = {
        parentId: tree.id,
      };
      getList(this.page.currentPage, this.page.pageSize, values).then(res => {
        const data = res.data.data.records.map(item => ({
          ...item,
          hasChildren: true,
        }));
        resolve(data);
      });
    },
    handlePublish(row) {
      publish(row.id)
        .then(res => {
          ElMessage({
            showClose: true,
            message: '发布成功',
            type: 'success',
          });
          this.onLoad(this.page);
        })
        .catch(err => {
          ElMessage({
            showClose: true,
            message: '发布失败',
            type: 'error',
          });
        });
    },
    handleUnPublish(row) {
      unpublish(row.id)
        .then(res => {
          ElMessage({
            showClose: true,
            message: '取消成功',
            type: 'success',
          });
          this.onLoad(this.page);
        })
        .catch(err => {
          ElMessage({
            showClose: true,
            message: '取消失败',
            type: 'error',
          });
        });
    },
  },
};
</script>

<style></style>
